﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading;
using Microsoft.Win32;
using System.IO;
using System.Configuration;

namespace GenericMethodInvoker
{
    public class PerformanceScenarioInitializer : IScenarioIntializer
    {
        string VSPerfCmdCommand = string.Format("{0}\\{1}", ConfigurationManager.AppSettings["VSPerfToolsPath"], "VSPerfCmd.exe");
        string VsPerfCLREnvCommand = string.Format("{0}\\{1}", ConfigurationManager.AppSettings["VSPerfToolsPath"], "VsPerfCLREnv.cmd");

        public void Initialize(string scenarioName)
        {
            ExecutePerformanceCommandLine(VsPerfCLREnvCommand, "/traceon", false);
            string VSPerfCmdParameters = string.Format("/start:trace /output:Report_{0}.vsp", scenarioName);
            ExecutePerformanceCommandLine(VSPerfCmdCommand, VSPerfCmdParameters, false);

        }
        
        private static void ExecutePerformanceCommandLine(string command, string parameters, bool waitForExit)
        {                        
            Process perfCmdProcess = new Process();

            perfCmdProcess.StartInfo.FileName = command;

            perfCmdProcess.StartInfo.Arguments = parameters;

            perfCmdProcess.StartInfo.UseShellExecute = false;

            perfCmdProcess.StartInfo.RedirectStandardInput = true;

            perfCmdProcess.Start();
            if (waitForExit)
            {
                perfCmdProcess.WaitForExit();
            }

            // Just wait 1 second for the process to cleanup
            Thread.Sleep(1000);
        }

        public void Cleanup(string scenarioName)
        {
            ExecutePerformanceCommandLine(VSPerfCmdCommand, "/shutdown", false);
        }
    }
}
